Converting between arrays and matrices
When using numpy, it is sometimes useful to do part of calculations using matrices rather than arrays. Thus it is interesting to be able to convert between the two types. This is easily done as follows, where we use the * operator in functions definitions. This enables to pass a variable number of parameters (in a form of an implicit lists, which is unpacked implicitely then after).
In [1]:
def tomat(*Z):
"""Converts the list of arrays in *Z to matrices"""
Out=[]
for iter in Z:
iter=mat(iter)
Out.append(iter)
return Out
def toarray(*Z):
"""Converts the list of matrices in *Z to arrays"""
Out=[]
for iter in Z:
iter=array(iter)
Out.append(iter)
return Out
A test:
In [2]:
A=randn(10,10)
B=randn(7,14)
C=[1, 3, 4]
D,E,F=tomat(A,B,C)
print(type(D))
G,H,L=toarray(D,E,F)
print(type(L))
#
A,B,C=tomat(A,B,C)
print(type(A))
A possible use is for situations like this: given two colomns vectors \(x\) and \(y\) and a matrix \(A\), compute \[z=x^T A y\]
In [11]:
x=randn(10)
y=randn(10)
A=randn(10,10)
# These are all arrays
print("Type of x: ",type(x))
# The expression computed using array's dot products:
z=x.dot(A).dot(y)
print(z)
# And computed using classical matrix notations
x,y,A=tomat(x,y,A)
print("Shape of x: ",shape(x))
zz=x*A*y.T
print(zz)
A script file 'tofromatarray.py' is available here
In [1]:
HTML(the_end(theNotebook))
Out[1]: